//
//  ViewController.m
//  UIImagePickController
//
//  Created by DYS on 15/12/11.
//  Copyright © 2015年 DYS. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
@property (nonatomic)UIImagePickerController *pickController;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (UIImagePickerController *)pickController{
    if (_pickController == nil) {
        _pickController = [[UIImagePickerController alloc] init];
        _pickController.delegate = (id)self;
        _pickController.editing = YES;
    }
    return _pickController;
}

- (IBAction)openLocal:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        self.pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:self.pickController animated:YES completion:nil];
    }
}

- (IBAction)takePhoto:(id)sender {
    self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:self.pickController animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"%@",info);
    UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //图片压缩，因为原图都是很大的，不必要传原图
    UIImage *scaleImage = [self scaleImage:originImage toScale:0.3];
    NSData *data;
    //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
    if (UIImagePNGRepresentation(scaleImage) == nil) {
        //将图片转换为JPG格式的二进制数据
        data = UIImageJPEGRepresentation(scaleImage, 1);
    } else {
        //将图片转换为PNG格式的二进制数据
        data = UIImagePNGRepresentation(scaleImage);
    }
    
    //将二进制数据生成UIImage
    UIImage *image = [UIImage imageWithData:data];
    self.iconImage.image = image;
    [self dismissViewControllerAnimated:NO completion:nil];

}

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
